package org.xxpay.pay.channel.witbytespay;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.domain.api.AbstractRes;
import org.xxpay.core.common.domain.api.ApiBuilder;
import org.xxpay.core.common.domain.api.PayRes;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.common.util.DateUtil;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.PayDigestUtil;
import org.xxpay.core.common.util.RandomStrUtils;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.mq.BaseNotify4MchPay;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;

import static org.xxpay.pay.channel.witbytespay.WitbytespayUtil.*;

public class WitbytespayPaymentService extends BasePayment {
    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    private static final MyLog _log = MyLog.getLog(WitbytespayPaymentService.class);

    @Override
    public String getChannelName() {
        return WitbytespayConfig.CHANNEL_NAME;
    }

    /**
     * 支付
     *
     * @param payOrder
     * @return
     */
    @Override
    public AbstractRes pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        AbstractRes retObj;
        switch (channelId) {
            case WitbytespayConfig.CHANNEL_NAME_H5PAY:
                retObj = h5Pay(payOrder);
                break;
//            case SaaspayConfig.CHANNEL_NAME_WEBPAY:
//                retObj = webPay(payOrder);
//                break;
//            case SaaspayConfig.CHANNEL_NAME_MINIPAY:
//                retObj = miniPay(payOrder);
//                break;
            default:
                return ApiBuilder.bizError("不支持的渠道[channelId=" + channelId + "]");
        }
        return retObj;
    }

    /**
     * H5支付
     *
     * @param payOrder
     * @return
     */
    public AbstractRes h5Pay(PayOrder payOrder) {
        WitbytespayConfig witbytespayConfig = new WitbytespayConfig(getPayParam(payOrder));
        PayRes retObj = ApiBuilder.buildSuccess(PayRes.class);
        DBApplicationConfig dbConfig = getDBApplicationConfig();
        //1. 组建请求报文
        WitbytespayUtil.H5PayBody reqBody = new WitbytespayUtil.H5PayBody();
        reqBody.ordercode = payOrder.getPayOrderId();
        reqBody.merchant_id = witbytespayConfig.getMerchant_id();
        reqBody.userid = payOrder.getChannelUser();
        reqBody.pay_method = "";
        reqBody.amount = payOrder.getAmount()*0.01 + "";
        reqBody.callback = super.getNotifyUrl(getChannelName(), dbConfig);
        reqBody.paytool = witbytespayConfig.getPaytool();
        reqBody.timestamp = String.valueOf(System.currentTimeMillis());
        reqBody.trade_ip = payOrder.getClientIp();
        reqBody.success_url = "";
        reqBody.fail_url = "";
        reqBody.goods_name = "";
        reqBody.goods_desc = "";
        reqBody.openid = "";
        reqBody.authcode = "";
        //2. 获取认证报文
        _log.info("request body:\n" + reqBody);
        String sort_str = PayDigestUtil.sortedStr(JSONObject.parseObject(reqBody.toString()));
        try {
            // 生成签名
            String sign = getSignatureByMD5(sort_str,witbytespayConfig.getSecret());
            reqBody.sign = sign;
            String reqUrl = witbytespayConfig.getReqUrl();
            // 请求地址
            String response = h5Request(reqUrl,reqBody.toString());
            JSONObject jsonobj = JSONObject.parseObject(response);
            String payurl = jsonobj.getString("payurl");
            _log.info("{}请求路径:{}", getChannelName(), payurl);
            retObj.setPayJumpUrl(payurl);      // 可以通过该地址跳转到支付中心界面完成支付(URL)
            StringBuffer payForm = new StringBuffer();
            payForm.append("<script>window.location.href = '" + payurl + "';</script>");
            retObj.setPayUrl(payForm.toString());
            retObj.setPayJumpUrl(payurl);
            retObj.setPayMethod(PayConstant.PAY_METHOD_JumpUrl);
            int updateCount = commonService.payOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
            _log.info("[{}]更新订单状态为支付中:payOrderId={},payUrl={},result={}", getChannelName(), payOrder.getPayOrderId(), payurl, updateCount);
            return retObj;
        } catch (Exception e) {
            _log.error(e, "");
            return ApiBuilder.bizError("操作失败!");
        }
    }


    /**
     * 查询订单
     *
     * @param payOrder
     * @return
     */
    @Override
    public QueryRetMsg query(PayOrder payOrder) {
        String logPrefix = "[" + getChannelName() + "主动查单]";
        WitbytespayConfig witbytespayConfig = new WitbytespayConfig(getPayParam(payOrder));
        WitbytespayUtil.QueryBody reqBody = new WitbytespayUtil.QueryBody();
        //1. 组建请求报文
        reqBody.ordercode = payOrder.getPayOrderId();
        reqBody.merchant_id = witbytespayConfig.getMerchant_id();
        reqBody.timestamp = String.valueOf(System.currentTimeMillis());
        String sort_str = PayDigestUtil.sortedStr(JSONObject.parseObject(reqBody.toString()));
        try {
            String sign = getSignatureByMD5(sort_str, witbytespayConfig.getSecret());
            reqBody.sign = sign;
            _log.info("{}request body:\n{}", logPrefix, reqBody);
            //3. 发送http请求，并解析返回信息
            String queryUrl = witbytespayConfig.getReqUrl() + "/"+reqBody.ordercode;
            String response = queryRequest(queryUrl, reqBody.toString());
            _log.info("{}response:\n{}", logPrefix, response);
            return QueryRetMsg.waiting();  //支付中
        } catch (Exception e) {
            _log.error(e, "");
            return QueryRetMsg.sysError();
        }
    }


    public static void main(String[] args) throws Exception {
        String testUrl = "https://gate.pay4.witbytes.com/api/v2/payments";
        //1. 组建请求报文
        String requestTime = DateUtil.date2Str(new Date(), DateUtil.FORMAT_YYYYMMDDHHMMSS);
        WitbytespayUtil.H5PayBody reqBody = new WitbytespayUtil.H5PayBody();
        reqBody.userid = "101";
        reqBody.ordercode = "T" + requestTime;
        reqBody.merchant_id = "222";
        reqBody.paytool = "alipay";
        reqBody.amount = "1";
        reqBody.pay_method = "";
        reqBody.callback = "http://127.0.0.1";
        reqBody.timestamp = String.valueOf(System.currentTimeMillis());
        reqBody.trade_ip = "";
        reqBody.success_url = "";
        reqBody.fail_url = "";
        reqBody.goods_name = "";
        reqBody.goods_desc = "";
        reqBody.openid = "";
        reqBody.authcode = "";
        System.out.println(reqBody.toString());
        String sort_str = PayDigestUtil.sortedStr(JSONObject.parseObject(reqBody.toString()));
        String sign = getSignatureByMD5(sort_str,"36274073aeeb6ae8e167d77376f8e29d");
        System.out.println(sign);
        reqBody.sign = sign;
        //2. 发送http请求，并解析返回信息
        String response = h5Request(testUrl,reqBody.toString());
        System.out.println("response:\n" + response);
    }
}
